package com.cloud.pole.merchant.controller;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import com.alibaba.druid.support.json.JSONUtils;
import com.cloud.pole.common.constant.CommonConstants;
import com.cloud.pole.common.constant.UserConstant;
import com.cloud.pole.common.exception.BaseException;
import com.cloud.pole.common.exception.ParamException;
import com.cloud.pole.common.msg.ApiRestResponse;
import com.cloud.pole.common.rest.BaseController;
import com.cloud.pole.common.util.TreeUtil;
import com.cloud.pole.merchant.biz.MenuBiz;
import com.cloud.pole.merchant.biz.ShopMerchantUserBiz;
import com.cloud.pole.merchant.constant.MerchantCommonConstant;
import com.cloud.pole.merchant.model.entity.Menu;
import com.cloud.pole.merchant.model.entity.ShopMerchantUser;
import com.cloud.pole.merchant.model.vo.FrontUser;
import com.cloud.pole.merchant.model.vo.MenuTree;
import com.cloud.pole.merchant.model.vo.RouteTree;
import com.cloud.pole.merchant.service.AuthService;
import com.cloud.pole.merchant.service.PermissionService;
import com.cloud.pole.merchant.service.ShopMerchantUserService;

import lombok.extern.slf4j.Slf4j;
import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.entity.Example.Criteria;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;


/**
 * ${DESCRIPTION}
 *
 * @author wanghaobin
 * @create 2017-06-08 11:51
 */
@RestController
@RequestMapping("user")
@Slf4j
public class UserController extends BaseController<ShopMerchantUserBiz, ShopMerchantUser> {
    @Autowired
    private PermissionService permissionService;
    @Autowired
    private MenuBiz menuBiz;
    @Autowired
    private ShopMerchantUserBiz userBiz;    
    @Autowired
    private AuthService authService;
    @Autowired
    private ShopMerchantUserService userService;
    
    /**
    * 查询用户的菜单、功能
     * @param token
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/front/info", method = RequestMethod.GET)
    @ResponseBody
    public ResponseEntity<?> getUserInfo(String token) throws Exception {
        FrontUser userInfo = permissionService.getUserInfo(token);
        if(userInfo==null) {
            return ResponseEntity.status(401).body(false);
        } else {
            return ResponseEntity.ok(userInfo);
        }
    }

    @RequestMapping(value = "/front/menus", method = RequestMethod.GET)
    public @ResponseBody
    List<MenuTree> getMenusByUsername(String token) throws Exception {
        return permissionService.getMenusByUsername(token);
    }
    
    @RequestMapping(value = "/front/menu/all", method = RequestMethod.GET)
    @ResponseBody
    public List<RouteTree> getAllRouteTree(String title) {
        Example example = new Example(Menu.class);
        Criteria criteria = example.createCriteria();
        if (StringUtils.isNotBlank(title)) {
        	criteria.andLike("title", "%" + title + "%");
        }
        criteria.andEqualTo("enabled", Menu.ENABLED_YES);
        List<Menu> listMenu = menuBiz.selectByExample(example);
        List<RouteTree> listRoute = getRouteTree(listMenu, MerchantCommonConstant.ROOT);
//        System.out.println(JSONUtils.toJSONString(listRoute));
        return listRoute;
    }
    
    private List<RouteTree> getRouteTree(List<Menu> menus,int root) {
        List<RouteTree> trees = new ArrayList<RouteTree>();
        RouteTree node = null;
        for (Menu menu : menus) {
            node = new RouteTree();
            BeanUtils.copyProperties(menu, node);
            node.setId(menu.getMenuId());
            node.setParentId(menu.getParentId());
            node.setName(menu.getTitle());
            node.setAuthority(menu.getCode());
            node.setComponent(menu.getAttr1());
            node.setIcon(menu.getIcon());
            node.setPath(menu.getCode());
            trees.add(node);
        }
        return TreeUtil.bulid(trees,root) ;
    }
    
    private List<MenuTree> getMenuTree(List<Menu> menus,int root) {
        List<MenuTree> trees = new ArrayList<MenuTree>();
        MenuTree node = null;
        for (Menu menu : menus) {
            node = new MenuTree();
            BeanUtils.copyProperties(menu, node);
            node.setLabel(menu.getTitle());
            node.setId(menu.getMenuId());
            trees.add(node);
        }
        return TreeUtil.bulid(trees,root) ;
    }
    
//    @ResponseBody
//    @RequestMapping(value = "/front/addUser", method = RequestMethod.POST)
//    public ApiRestResponse<Boolean> addUser(@RequestBody User user) {
//    	try {
//    		//验证用户名是否存在
//    		if(authService.checkUserName(user.getUsername())) {
//    			return ApiRestResponse.fail("账户已经存在，请替换", false);
//    		}
//    		else {
//    			userBiz.insertSelective(user);
//    		}
//			return ApiRestResponse.success(CommonConstants.STATUS_OK_MESSAGE, true);
//		} catch (BaseException e) {
//			return ApiRestResponse.fail(e.getStatus(), e.getMessage(), null);
//		} catch (Exception e) {
//			log.error(CommonConstants.STATUS_ERROR_MESSAGE + "{}", e.getMessage(), e);
//			return ApiRestResponse.fail(CommonConstants.STATUS_ERROR_MESSAGE, null);
//		}
//    }
    
    
//    @RequestMapping(value = "/front/resetPwd/{id}", method = RequestMethod.PUT)
//    @ResponseBody
//    public ApiRestResponse<Boolean> resetPwd(@RequestBody Map<String, Object> params) {
//    	try {
//    		Integer userId = (Integer)params.get("userId");
//    		String password = (String)params.get("password1");
//    		User user = userBiz.selectById(userId);
//    		if(user == null) {
//    			return ApiRestResponse.fail("参数错误", false);
//    		}
//    		if(user != null) {
//    	        String passwordEncoder = new BCryptPasswordEncoder(UserConstant.PW_ENCORDER_SALT).encode(password);
//        		user.setPassword(passwordEncoder);
//        		userBiz.updateSelectiveById(user);
//    		}
//			return ApiRestResponse.success(CommonConstants.STATUS_OK_MESSAGE, true);
//		} catch (BaseException e) {
//			return ApiRestResponse.fail(e.getStatus(), e.getMessage(), null);
//		} catch (Exception e) {
//			log.error(CommonConstants.STATUS_ERROR_MESSAGE + "{}", e.getMessage(), e);
//			return ApiRestResponse.fail(CommonConstants.STATUS_ERROR_MESSAGE, null);
//		}
//    }
    
    @RequestMapping(value = "/front/getMyInfo", method = RequestMethod.GET)
    @ResponseBody
    public ApiRestResponse<ShopMerchantUser> getMyInfo(
    		@RequestHeader(defaultValue = "") String token) {
    	try {
			ParamException.err(StringUtils.isBlank(token), "token不能为空");    		
    		return ApiRestResponse.success(CommonConstants.STATUS_OK_MESSAGE, userService.getMyInfo(token));
		} catch (BaseException e) {
			return ApiRestResponse.fail(e.getStatus(), e.getMessage(), null);
		} catch (Exception e) {
			log.error(CommonConstants.STATUS_ERROR_MESSAGE + "{}", e.getMessage(), e);
			return ApiRestResponse.fail(CommonConstants.STATUS_ERROR_MESSAGE, null);
		}
    }
    
    @RequestMapping(value = "/front/modifyMyInfo", method = RequestMethod.PUT)
    @ResponseBody
    public ApiRestResponse<Boolean> modifyMyInfo(
    		@RequestHeader(defaultValue = "") String token,
    		@RequestBody ShopMerchantUser user) {
    	try {
			ParamException.err(StringUtils.isBlank(token), "token不能为空");    		
			userService.modifyMyInfo(token, user);
    		return ApiRestResponse.success(CommonConstants.STATUS_OK_MESSAGE, true);
		} catch (BaseException e) {
			return ApiRestResponse.fail(e.getStatus(), e.getMessage(), null);
		} catch (Exception e) {
			log.error(CommonConstants.STATUS_ERROR_MESSAGE + "{}", e.getMessage(), e);
			return ApiRestResponse.fail(CommonConstants.STATUS_ERROR_MESSAGE, null);
		}
    }
    
    @RequestMapping(value = "/front/modifyMyPwd", method = RequestMethod.PUT)
    @ResponseBody
    public ApiRestResponse<Boolean> modifyMyPwd(
    		@RequestHeader(defaultValue = "") String token, @RequestBody Map<String, Object> params) {
    	try {
    		String oldPwd = (String)params.get("oldPwd");
    		String newPwd = (String)params.get("newPwd");
    		String newConfirmPwd = (String)params.get("newConfirmPwd");
			ParamException.err(StringUtils.isBlank(token), "token不能为空");    		
			ParamException.err(StringUtils.isBlank(oldPwd), "当前密码不能为空");    		
			ParamException.err(StringUtils.isBlank(newConfirmPwd), "确认密码不能为空");    		
			userService.modifyMyPassWord(token, oldPwd, newPwd);
    		return ApiRestResponse.success(CommonConstants.STATUS_OK_MESSAGE, true);
		} catch (BaseException e) {
			return ApiRestResponse.fail(e.getStatus(), e.getMessage(), null);
		} catch (Exception e) {
			log.error(CommonConstants.STATUS_ERROR_MESSAGE + "{}", e.getMessage(), e);
			return ApiRestResponse.fail(CommonConstants.STATUS_ERROR_MESSAGE, null);
		}
    }
    
    @ResponseBody
    @RequestMapping(value = "/front/checkUserName", method = RequestMethod.GET)
    public ApiRestResponse<Boolean> checkUserName(String userName) {
    	try {
			ParamException.err(StringUtils.isBlank(userName), "用户名不能为空");    		
    		return ApiRestResponse.success(CommonConstants.STATUS_OK_MESSAGE, authService.checkUserName(userName));
		} catch (BaseException e) {
			return ApiRestResponse.fail(e.getStatus(), e.getMessage(), null);
		} catch (Exception e) {
			log.error(CommonConstants.STATUS_ERROR_MESSAGE + "{}", e.getMessage(), e);
			return ApiRestResponse.fail(CommonConstants.STATUS_ERROR_MESSAGE, null);
		}
    }
}
